package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ：CC
 * @date ：Created in 2019/12/13
 * @description ：权限管理业务层接口实现类
 * @version: 1.0
 */
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {

    //依赖注入
    @Autowired
    private PermissionDao permissionDao;

    //新增权限
    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Permission> page = permissionDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    //根据id查询权限
    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    //编辑权限
    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    //删除权限
    @Override
    public void deleteById(Integer id) {
        //判断权限是否被关联
        long count = permissionDao.findCountByPermissionId(id);
        if(count > 0){
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.PERMISSION_ASSOCIATED);
        }else {
            //没有被关联，可以删除
            permissionDao.deleteById(id);
        }
    }
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }
}
